/*
 * @Author         : zhanglk
 * @Date           : 2020-05-29 14:21:20
 * @LastEditTime   : 2020-09-25 14:41:26
 * @LastEditors    : zhanglk
 * @Description    :
 * @FilePath       : \wxApp\src\utils\request.ts
 */
import interceptors from "./interceptors";
import defaultConfig from "@/config";
import { useUserStoreHook } from '@/store/user';
// import //Logger from ".///Logger";

interceptors.forEach(interceptorItem => uni.addInterceptor('request', interceptorItem));

export interface OptionsType {
	method?: "POST" | "GET";
	param?: { [index: string]: any }; // param部分
	bodyHead?: API.Request<any>; // 自定义标准头
}

export interface RequestType {
	<T = any>(
		url: string,
		options?: OptionsType,
		header?: Record<string, any>
	): Promise<T>;
}

// 获取请求头部
const getBodyHead = (options: OptionsType): API.Request<any> => {
	const { bodyHead } = options;
	const loginDataStore = useUserStoreHook()
	let { accessToken = '', channel = 'APP', userId = 0, organId = 0 } = loginDataStore;
	return {
		accessToken: accessToken,
		spCode: 'TZB_001',
		channel: channel || "APP",
		userId: userId || 0,
		organId: organId || 0,
		reqSeq: Date.now().toString(),
		...bodyHead
	};
};

export const request: RequestType = (
	url: string,
	options: OptionsType = { method: "post", param: {} },
	header?: Record<string, any>
) => {
	// 构建请求
	const body: API.Request<any> = {
		// user_id:39,
		phone: uni.getStorageSync('phone') || '',
		user_id: uni.getStorageSync('user_id') || '',
		...options,

	};
	console.log('我是请求头', body, options)
	return new Promise((resolve, reject) => {
		let httpurl = `${defaultConfig.apiHost}?i=1&route=${url}`;
		console.log(`${httpurl} request`, body);
		uni.request({
			url: httpurl,
			data: body,
			method: options.method || "POST",
			header: header || { "content-type": "application/json" }
		})
			.then((res: any) => {
				console.log(`${httpurl} response`, res.data);
				if (res.data && res.data.result !== 1) {
					// uni.showToast({
					// 	title: `${res.data.msg.msg}`,
					// 	icon: "none"
					// });
					if ('300' == res.data.result) {
						useUserStoreHook().loginOut()
					}
				}
				resolve(res.data);
			})
			.catch(e => {
				reject(e);
			});
	});
};


